package com.cqie.rbac.realm;

import com.cqie.rbac.entity.SysUser;
import com.cqie.rbac.exception.BusinessException;
import com.cqie.rbac.mapper.SysUserMapper;
import com.cqie.rbac.util.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author 夏兵
 * @Date 2021/9/17
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser user = (SysUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(user.getPermissionCodes());
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println(authenticationToken);
        String token = (String) authenticationToken.getPrincipal();
        try {
            JwtUtils.checkToken(token);
        } catch (SignatureException e) {
            e.printStackTrace();
            throw new BusinessException("5000", "无效签名");
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
            throw new BusinessException("5000", "不支持的签名");
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            throw new BusinessException("5000", "token过期");
        } catch (MalformedJwtException e) {
            e.printStackTrace();
            throw new BusinessException("5000", "不支持的签名格式");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("5000", "token无效");
        }
        if (token == null) {
            throw new BusinessException("4003", "登录认证失败");
        }
        String uId = JwtUtils.getMemberIdByToken(token);
        SysUser user = sysUserMapper.selectById(uId);
        if (user == null) {
            throw new BusinessException("4000", "用户不存在");
        }
        user.setPermissionCodes(sysUserMapper.queryUserPermissionCode(Long.parseLong(uId)));
        return new SimpleAuthenticationInfo(user, token, this.getName());
    }
}
